﻿using LightCAD.Core;
using LightCAD.Runtime;
using LightCAD.WinForm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Weikio.PluginFramework.Abstractions;

namespace LightCAD.UI
{
    public class App : IApp
    {
        public static App Current { get; private set; }

        static App()
        {
            Current = new App();
        }

        private string[] args;
        private IUISystem uiSystem;

        public IWindow ActiveWindow { get; private set; }
        public async void Initialize(string[] args)
        {
            uiSystem = new UISystem();
            LcDocument.RegistElementTypes(BuiltinElementType.All);
            LightCAD.Drawing.Loader.Initilize();
            await PluginManager.LoadPlugins();

        }
        public void OnUIInitilized(IMainUI mainUI)
        {
            ActiveWindow = (IWindow)mainUI.ParentWin;
            this.ActiveWindow = (IWindow)mainUI.ParentWin;
            AppRuntime.Initilize(this, uiSystem, mainUI, args);

        }

        private List<MainUIWindow> MainWinList = new List<MainUIWindow>();
        public void CreateMainWindow(LcDocument doc=null)
        {
            var mainWin = new MainUIWindow(doc!=null);
            mainWin.FormClosed += MainWin_FormClosed;
            mainWin.Show();
            MainWinList.Add(mainWin);
            if(doc != null)
            {
                mainWin.mainUI.OpenDrawingTab(doc);
            }
        }
        public bool IsExist { get; private set; }
        private void MainWin_FormClosed(object? sender, FormClosedEventArgs e)
        {
            var mainWin = sender as MainUIWindow;
            MainWinList.Remove(mainWin);
            if (MainWinList.Count == 0)
            {
                this.IsExist = true;
                Application.Exit();
                
            }
        }
    }
}
